package com.tiny.thread.synchronize.unsynch;

import java.util.Arrays;

/**
 * 具有transfer功能的银行类
 * Created by zhumenglong on 2017/3/12.
 */
public class Bank {

    private final double[] accounts;

    public Bank(int n, double initialBalence) {
        accounts = new double[n];
        Arrays.fill(accounts,initialBalence);
    }

    /**
     * 转账
     *
     * @param from   来源账户
     * @param to     接收账户
     * @param amount 转账金额
     */
    public void transfer(int from, int to, double amount) {
        //警告：在多线程环境下不安全
        if (accounts[from] < amount) return;
        System.out.print(Thread.currentThread());
        accounts[from] -= amount;
        System.out.printf(" %10.2f from %d to %d", amount, from, to);
        accounts[to] += amount;
        System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());

    }

    /**
     * 获取银行的全部余额
     *
     * @return 全部余额
     */
    public double getTotalBalance() {
        double sum = 0;

        for (double a : accounts)
            sum += a;

        return sum;
    }

    /**
     * 获取银行账户的数目
     * @return  账户数目
     */
    public int size()
    {
        return accounts.length;
    }
}
